import React, { useState } from 'react';
import { Button, Col, Form, Input, Row, Table, Card, DatePicker, Select } from 'antd';
import { useAntdTable, useRequest } from 'ahooks';
import { IAntdTablePageParams } from '@/types/type';
import dayjs from 'dayjs';
import {
  exportRtkLicenseList,
  queryRtkLicenseList,
} from '@/services/mapServiceManagement/activationRecord';
import { fetchBrand } from '@/services/intelligent/trackingInfo';
import styles from './index.less';
import { ColumnsType } from 'antd/es/table';
import { RtkLicenseListItem } from '@/types/mapServiceManagement/activationRecord';
import { downloadFileByUrl } from '@/utils/utils';
import { connect } from 'dva';
import { filterAuth } from '@/support/common';

const { RangePicker } = DatePicker;

const rtkStatusMap = new Map([
  [0, ['---', 'fail']],
  [1, ['注册', 'register']],
  [2, ['激活', 'active']],
  [3, ['过期', 'expire']],
]);

const licenseStatusMap = new Map([
  [0, ['---', 'fail']],
  [1, ['注册', 'register']],
  [2, ['激活', 'active']],
  [3, ['过期', 'expire']],
]);
const getTableData = async ({ current, pageSize }: IAntdTablePageParams, formData: any) => {
  let { activeTime, ...rest } = formData;
  // pageNum默认从0开始
  let params: any = {
    pageNum: current - 1,
    pageSize,
    ...rest,
  };
  if (activeTime) {
    let [beginActivationDate, endActivationDate] = activeTime;
    params.beginActivationDate = dayjs(beginActivationDate).format('YYYY-MM-DD');
    params.endActivationDate = dayjs(endActivationDate).format('YYYY-MM-DD');
  }
  let { data } = await queryRtkLicenseList(params);
  return {
    success: true,
    total: data.total,
    list: data.records,
  };
};
const mapStateToProps = (state:any) => ({
  menu: state.menu,
}
);
export default connect(mapStateToProps)((props: any) => {
  const { menu: { permissions } } = props;
  const [showDetail, setShowDetail] = useState(false);

  const [form] = Form.useForm();
  const { tableProps, search, params } = useAntdTable(getTableData, {
    defaultPageSize: 10,
    form,
  });
  const { submit, reset } = search;
  const { current, pageSize } = params[0] || ({} as any);
  const { data: brandOptions = [], loading: brandLoading = true } = useRequest(fetchBrand);

  const onExportTask = async () => {
    const { brandId, dataCenter, activeTime } = params[1] || ({} as any);
    let exportParams: any = {
      brandId,
      dataCenter,
    };
    if (activeTime) {
      let [beginActivationDate, endActivationDate] = activeTime;
      exportParams.beginActivationDate = dayjs(beginActivationDate).format('YYYY-MM-DD');
      exportParams.endActivationDate = dayjs(endActivationDate).format('YYYY-MM-DD');
    }
    let { data: url } = await exportRtkLicenseList(exportParams);
    // 文件名格式：车辆RTK&高精地图注册激活记录（年月日时分）202410151025.csv
    downloadFileByUrl(url, `车辆RTK&高精地图注册激活记录${dayjs().format('YYYYMMDDHHmm')}.csv`);
  };

  const onDetail = () => {
    setShowDetail(true);
  };

  const onBack = () => {
    setShowDetail(false);
  };

  const columns: ColumnsType<RtkLicenseListItem> = [
    {
      title: '序号',
      dataIndex: 'no',
      align: 'center',
      width: 70,
      render: (text: any, record: any, index: any) => {
        return index + 1 + (current - 1) * pageSize;
      },
    },
    {
      title: 'VIN',
      dataIndex: 'vin',
      align: 'center',
    },
    {
      title: 'RTK状态',
      dataIndex: 'rtkStatus',
      align: 'center',
      render(value: number) {
        if (value === undefined || value === null) {
          return '--';
        }
        let [text, color] = rtkStatusMap.get(value) || [];
        return <div className={styles[color]}>{text}</div>;
      },
    },
    {
      title: 'RTK激活时间',
      dataIndex: 'rtkActivationDate',
      align: 'center',
      render(value: any) {
        if (value === null || value === undefined) {
          return '--';
        }
        return dayjs(value).format('YYYY-MM-DD');
      },
    },
    {
      title: 'RTK过期时间',
      dataIndex: 'rtkExpireDate',
      align: 'center',
      render(value: any) {
        if (value === null || value === undefined) {
          return '--';
        }
        return dayjs(value).format('YYYY-MM-DD');
      },
    },
    {
      title: '高精地图状态',
      dataIndex: 'licenseStatus',
      align: 'center',
      render(value: number) {
        if (value === undefined || value === null) {
          return '--';
        }
        let [text, color] = licenseStatusMap.get(value) || [];
        return <div className={styles[color]}>{text}</div>;
      },
    },
    {
      title: '高精地图激活时间',
      dataIndex: 'licenseActivationDate',
      align: 'center',
      render(value: any) {
        if (value === null || value === undefined) {
          return '--';
        }
        return dayjs(value).format('YYYY-MM-DD');
      },
    },
    {
      title: '高精地图过期时间',
      dataIndex: 'licenseExpireDate',
      align: 'center',
      render(value: any) {
        if (value === null || value === undefined) {
          return '--';
        }
        return dayjs(value).format('YYYY-MM-DD');
      },
    },
    {
      title: '操作',
      dataIndex: 'opt',
      align: 'center',
      fixed: 'right',
      render: (text: any, record: any) => {
        return [
          <Button type="link" key="detail" onClick={onDetail}>
            查看详情
          </Button>,
        ];
      },
    },
  ];

  const detailLeftTableProps: ColumnsType<RtkLicenseListItem> = [
    {
      title: '序号',
      dataIndex: 'no',
      align: 'center',
      width: 60,
      render: (text: any, record: any, index: any) => {
        return index + 1;
      },
    },
    {
      title: 'RTK注册时间',
      dataIndex: 'rtkRegisterDate',
      align: 'center',
      render(value: any) {
        if (value === null || value === undefined) {
          return '--';
        }
        return dayjs(value).format('YYYY-MM-DD');
      },
    },
    {
      title: 'RTK激活时间',
      dataIndex: 'rtkActivationDate',
      align: 'center',
      render(value: any) {
        if (value === null || value === undefined) {
          return '--';
        }
        return dayjs(value).format('YYYY-MM-DD');
      },
    },
    {
      title: 'RTK过期时间',
      dataIndex: 'rtkExpireDate',
      align: 'center',
      render(value: any) {
        if (value === null || value === undefined) {
          return '--';
        }
        return dayjs(value).format('YYYY-MM-DD');
      },
    },
  ];

  const detailRightTableProps: ColumnsType<RtkLicenseListItem> = [
    {
      title: '序号',
      dataIndex: 'no',
      align: 'center',
      width: 60,
      render: (text: any, record: any, index: any) => {
        return index + 1;
      },
    },
    {
      title: '高精地图注册时间',
      dataIndex: 'licenseRegisterDate',
      align: 'center',
      render(value: any) {
        if (value === null || value === undefined) {
          return '--';
        }
        return dayjs(value).format('YYYY-MM-DD');
      },
    },
    {
      title: '高精地图激活时间',
      dataIndex: 'licenseActivationDate',
      align: 'center',
      render(value: any) {
        if (value === null || value === undefined) {
          return '--';
        }
        return dayjs(value).format('YYYY-MM-DD');
      },
    },
    {
      title: '高精地图过期时间',
      dataIndex: 'licenseExpireDate',
      align: 'center',
      render(value: any) {
        if (value === null || value === undefined) {
          return '--';
        }
        return dayjs(value).format('YYYY-MM-DD');
      },
    },
  ];

  return (
    <div>
      <Card className={showDetail ? styles['hide'] : styles['show']}>
        <Form form={form} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }}>
          <Row gutter={24}>
            <Col span={5}>
              <Form.Item label="品牌" name="brandId">
                <Select
                  options={brandOptions.map((item: any) => {
                    const { brandName, brandCode } = item;
                    return {
                      label: brandName,
                      value: brandCode,
                    };
                  })}
                  loading={brandLoading}
                  placeholder="请选择品牌"
                  allowClear
                />
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item label="vin" name="vin">
                <Input placeholder="请输入车辆VIN码" allowClear />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="激活日期" name="activeTime">
                <RangePicker allowClear />
              </Form.Item>
            </Col>
            <Col span={5}>
              <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                <Button type="primary" onClick={submit}>
                  查询
                </Button>
                <Button onClick={reset} style={{ marginLeft: 16 }}>
                  重置
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
        <div className={styles['mb-12']}>
          {filterAuth('activationRecord_export', permissions, props.location.pathname) ? (
            <Button type="primary" onClick={onExportTask} className={styles['ml-12']}>
              导出任务
            </Button>
          ) : null}
        </div>
        <Table
          columns={columns}
          rowKey="id"
          scroll={{ x: 'max-content' }}
          bordered
          {...tableProps}
        />
      </Card>
      <Card className={showDetail ? styles['show'] : styles['hide']}>
        <Row>
          <Col span={12}>
            <Button style={{ marginBottom: 16, marginRight: 16 }} type={'primary'} onClick={onBack}>
              返回
            </Button>
          </Col>
        </Row>
        <Row className={styles['mb-12']}>
          <Col span={10}>
            <Table
              columns={detailLeftTableProps}
              rowKey="id"
              scroll={{ x: 'max-content' }}
              bordered
              {...tableProps}
              pagination={false}
            />
          </Col>
          <Col span={12} offset={2}>
            <Table
              columns={detailRightTableProps}
              rowKey="id"
              scroll={{ x: 'max-content' }}
              bordered
              {...tableProps}
              pagination={false}
            />
          </Col>
        </Row>
        <div>
          <span>共</span>
          <span className={styles['m-5']}>{tableProps.pagination.total}</span>
          <span>条记录</span>
          <span className={styles['ml-12']}>第</span>
          <span className={styles['m-5']}>
            {current}/{Math.ceil(tableProps.pagination.total / pageSize)}
          </span>
          <span>页</span>
        </div>
      </Card>
    </div>
  );
})
